<template>
	<div class="w100 h100" ref="container">
		<div style="position: absolute; z-index: 10" class="flex-center w100 h100" v-show="loading">
			<dv-decoration :scale="2">
				<span class="fw" style="font-size: 30px"> {{ percentComplete }}% </span>
			</dv-decoration>
		</div>
		<my-compass :keyType="keyType" />
	</div>
</template>

<script setup name="comprehensive/pressure">
import { machineInfo } from '@a/pressure'
import myLabel from '@c/common/my-label.vue'
import { DBUtil } from '@u/indexedDB'
import { useResizeObserver, THREE, GLTFloaderFn, cameraFn, compassRotate, rendererFn, labelRendererFn, CSS3DSprite, keyType } from '@u/threeMinx'

let container = ref(null), // 模型渲染的Demo节点
	renderer, //  WebGLRenderer渲染器
	scene, // 场景
	camera, // 相机
	labelRenderer,
	loading = ref(false),
	percentComplete = ref(0),
	cameraRender

// 组件宽高
let width, height
useResizeObserver(container, (entries) => {
	width = entries[0].contentRect.width
	height = entries[0].contentRect.height
	camera.aspect = width / height
	camera.updateProjectionMatrix()
	renderer.setSize(width, height)
	labelRenderer.setSize(width, height)
})
// 初始化生命周期
onMounted(() => {
	loading.value = true
	init()
})
onBeforeUnmount(() => {
	cancelAnimationFrame(requestAnimationFrameIndex)
	// 释放显存
	renderer?.dispose()
	// 释放内存
	container = null
	scene = null
	labelRenderer = null
})

function init() {
	// 场景
	scene = new THREE.Scene()
	// 相机
	camera = new THREE.PerspectiveCamera(45, width / height, 1, 2000)
	camera.position.set(-9, 3, 5)
	camera.lookAt(-2.96, 2.12, -3.82)
	scene.add(camera)
	// 相机旋转移动
	cameraRender = cameraFn(camera)
	labelRenderer = labelRendererFn(container)
	renderer = rendererFn(container)
	// 灯光
	lights()
	// 加载器
	loaderFn()
}
let objects = [],
	model,
	labelObj = new THREE.Group()

function loaderFn() {
	new DBUtil().get(`${import.meta.env.VITE_APP_BASE_BASE || '/'}model/压风系统.glb`).then((blob) => {
		let url = URL.createObjectURL(blob)
		GLTFloaderFn.load(
			url,
			(object) => {
				loading.value = false
				model = object.scene
				scene.add(model)
				objects = model.getObjectByName('墙').children
				for (let i = 1; i < 4; i++) {
					const obj = model.getObjectByName('主体').clone()
					obj.name = `主体${i}`
					obj.position.x = obj.position.x + i * 4
					scene.add(obj)
				}
				// 添加label
				scene.add(labelObj)
				machineInfoFn()
				// 渲染器
				render()
			},
			(xhr) => {
				if (xhr.lengthComputable) percentComplete.value = Math.round((xhr.loaded / xhr.total) * 100, 2)
			}
		)
	})
}

// 灯光
function lights() {
	// 自然光
	scene.add(new THREE.AmbientLight('#fff', 0.8))
}

// 添加label逻辑
let labelData = ref([])
function machineInfoFn() {
	labelData.value = []
	labelObj.clear()
	machineInfo().then((res) => {
		res.data.forEach((item) => {
			labelData.value.push({
				name: item.machineName,
				list: [
					{
						title: '运行状态',
						val: item.runningState
					},
					{
						title: '供气压力',
						val: item.pressure,
						suffix: 'MPa'
					},
					{
						title: '排气温度',
						val: item.temperature,
						suffix: '℃'
					},
					{
						title: '运行时间',
						val: item.runningTime,
						suffix: 'h'
					}
				]
			})
		})
		nextTick(() => {
			const { x, y, z } = model.getObjectByName('主体').position
			for (let i = 0, len = labelData.value.length; i < len; i++) {
				label(i, [x + i * 4 - 1, y, z])
			}
		})
	})
}
function label(key, position) {
	const dom = createApp(myLabel, {
		data: labelData.value[key],
		callBack: () => {
			console.log(labelData.value[key])
		}
	}).mount(document.createElement('div')).$el
	const pointLabel = new CSS3DSprite(dom)
	pointLabel.position.set(...position)
	pointLabel.scale.set(0.01, 0.01, 0.01)
	labelObj.add(pointLabel)
}

// 渲染逻辑
let requestAnimationFrameIndex
function render() {
	// 漫游
	keyType.value = cameraRender(objects)
	compassRotate(camera)
	labelRenderer?.render(scene, camera)
	renderer?.render(scene, camera)
	requestAnimationFrameIndex = requestAnimationFrame(render)
}
</script>
